package com.kimguo.shiro;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroBean {
	
	@Qualifier("defaultWebSecurityManager")
	@Autowired
	DefaultWebSecurityManager defaultWebSecurityManager;
	
	@Qualifier("userRealm")
	@Autowired
	UserRealm userRealm;

	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean () {
		ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
		filterFactoryBean.setSecurityManager(defaultWebSecurityManager);
		Map<String, String> map = new HashMap<String, String>();
		map.put("/all","authc");
		map.put("/one","authc");
		
		//拦截未授权
		map.put("/all","perms[user:all]");
		map.put("/one","perms[user:one]");

        
		filterFactoryBean.setLoginUrl("/login");
		filterFactoryBean.setUnauthorizedUrl("/permission");
		filterFactoryBean.setFilterChainDefinitionMap(map);
		
		return filterFactoryBean;
	}
	
	@Bean
	public DefaultWebSecurityManager webSecurityManager () {
		DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
		defaultWebSecurityManager.setRealm(userRealm);
		return defaultWebSecurityManager;
	}
	
	@Bean
	public HashedCredentialsMatcher hashedCredentialsMatcher () {
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		credentialsMatcher.setHashAlgorithmName("md5");
		credentialsMatcher.setHashIterations(2);
		return credentialsMatcher;
	}
	
}
